class M {
	constructor(){
		this.rec = null;
		this.recBlob = null;
		this.param = null;
		this.coreType = null;
		this.refText = null;
		this.refPinyin = null;
		this.isRecoding = false;
	}
	current(){
		const SERVER = "https://nihaocity.smwho.cn/";
		const TEST = "https://nihaotest.smwho.cn/";
		const LOCAL = "./";
		if (window.location.href.indexOf("localhost")>-1) return LOCAL;
		else if (window.location.href.indexOf("test.")>-1) return TEST;
		else return SERVER;
	}
		

	/**
	* 显示调试信息
	*/
	d(...aegs) {
		if (aegs.length==1) console.log(aegs[0]);
		else console.log(aegs);
	}
	/**
	* 将对象保存在浏览器的存储空间中
	*/
	saveItem(key,val){
	  if (val==null) localStorage.removeItem(key);
	  else localStorage.setItem(key, val);
	}
	saveJson(key,val){
	  this.saveItem(key,JSON.stringify(val));
	}
	/**
	* 从浏览器的存储空间中按照键值取出对象
	*/
	loadItem(key){
	  return localStorage.getItem(key);
	}
	loadJson(key){
		let rtn = this.loadItem(key);
		if (rtn) return JSON.parse(rtn);
	  else return null;
	}
	loadInt(key){
		let rtn = this.loadItem(key);
		if (rtn) return parseInt(rtn);
	  else return null;
	}
	/**
	* 从浏览器的存储空间中删除键值和对象
	*/
	removeItem(key){
	  localStorage.removeItem(key);
	}
	/**
	* 根据id找节点
	*/
	getNode(id){
		return document.getElementById(id);
	}
	/**
	* 显示或隐藏节点
	*/
	display(id,show){
		let div =document.getElementById(id);
		if (show) div.style.display="";
		else div.style.display="none";
	}
	getRare(i){
		if (i<1) return "💚💚💚💚💚";
		else if (i<3) return "💚💚💚💚🤍";
		else if (i<7) return "💚💚💚🤍🤍";
		else if (i<15) return "💚💚🤍🤍🤍";
		else return "💚🤍🤍🤍🤍";
	}
	getPrice(i){
		if (i<1) return 1600;
		else if (i<3) return 800;
		else if (i<7) return 400;
		else if (i<15) return 200;
		else return 100;
	}
	getTransparency(i){
		if (i<1) return 1;
		else if (i<3) return 0.8;
		else if (i<7) return 0.6;
		else if (i<15) return 0.4;
		else return 0.2;
	}	
	newNode(name){
		return document.createElement(name);
	}
	getBookNo(i){
		return (Math.floor( i / 16 ) + 1)+"-"+(Math.floor( (i%16) / 4 ) + 1)+"-" +((i%4) + 1);
	}	
	async callAPI(param){
		let d = this.d;
	  const p = await new Promise((resolve)=>{
		  if (param.webapi){
		    //钱包地址是必须的，作为判断用户的依据
		    param.address = "0x62dCd869f1C69c54104a34Edabe6A883a1824825";
		    var api = new XMLHttpRequest();
		    api.onreadystatechange = function(){
		      if (api.readyState==4 && api.status == 200){
						try{
							let data = nullToStr(JSON.parse(api.responseText));
							resolve(data);				
						}catch(e){
							d(e);
							resolve(false);	
						}
		      }
		    };
		    //设置函数计算的地址
		    var url = "https://nihaocitytest.smwho.cn/" + param.webapi;
		    api.open("POST", url);
		    api.setRequestHeader('content-type', 'application/json');
		    //提交数据
		    api.send(JSON.stringify(param));
		  }else{
		    d("no webapi");
				resolve(false);	
		  }
			function nullToStr(data) {
			  for (var x in data) {
			    if (data[x] === null) { 
			      data[x] = '';
			    } else {
			      // 遍历数组递归继续处理
			      if (Array.isArray(data[x])) { 
			        data[x] = data[x].map(z => {
			          return nullToStr(z);
			        });
			      }
			      // json也递归继续处理
			      if(typeof(data[x]) === 'object'){ 
			        data[x] = nullToStr(data[x]);
			      }
			    }
			  }
			  return data;
			}	
	  });
	  return p;
	}	

	/**调用open打开录音请求好录音权限**/
	recOpen(recwave){
		let wave;
		this.rec=null;
		this.recBlob=null;
		var newRec=Recorder({
			type:"wav",sampleRate:16000,bitRate:16,channel:1
			,onProcess:function(buffers,powerLevel,bufferDuration,bufferSampleRate,newBufferIdx,asyncEnd){
				if (recwave){
					//可视化图形绘制
					wave.input(buffers[buffers.length-1],powerLevel,bufferSampleRate);
				}
			}
		});
		this.callAPI({webapi:"getSig"}).then((data)=>{this.param=data});
		newRec.open(()=>{//打开麦克风授权获得相关资源
			this.rec = newRec;
			//取得签名
			if (recwave){
				//此处创建这些音频可视化图形绘制浏览器支持妥妥的
				wave=Recorder.FrequencyHistogramView({elem:"."+recwave});
			}			
		},function(msg,isUserNotAllow){
			alert("用户拒绝未授权或不支持");
		});
	};
	/**关闭录音，释放资源**/
	recClose(){
		if(this.rec){
			this.rec.close();
		};
	};
	/**取消录音**/
	recCancel(){
		if(this.rec && this.isRecoding){
			this.rec.stop();
			this.recBlob = null;
			this.isRecoding = false;
		}
	}

	/**开始录音**/
	recStart(coreType,refText,refPinyin){
		if(this.rec && Recorder.IsOpen() && !this.isRecoding){
			this.isRecoding = true;
			this.recBlob = null;
			this.coreType = coreType;
			this.refText = refText;
			this.refPinyin = refPinyin;
			this.rec.start();
		};
	};
	/**结束录音，得到音频文件，并进行语音评测**/
	async recStop(){
	  const p = await new Promise((resolve)=>{
			if(!(this.rec && Recorder.IsOpen() && this.isRecoding)) resolve(false);
			else{
				this.rec.stop((blob,duration)=>{
					this.isRecoding = false;
					this.recBlob = blob;
					var param = {
						connect:{
							cmd:'connect',
							param:{
								sdk:{
									version:16777472,
									source:9,
									protocol:2
								},
								app:{
									applicationId:'16293660770000a6',
									sig:this.param.sig,
									timestamp:this.param.timestamp
								}
							}
						},
						start:{
							cmd:'start',
							param:{
								audio:{
									audioType:'wav',
									sampleRate:16000,
									channel:1,
									sampleBytes:2
								},
								app:{
									applicationId:'16293660770000a6',
									sig:this.param.start_sig,
									userId:this.param.userId,
									timestamp:this.param.start_timestamp
								},
								request:{
									coreType:this.coreType,
									refText:this.refText,
									refPinyin:this.refPinyin.replaceAll("0","5"),
									attachAudioUrl:1
								}
							}
						}
					};
					var form=new FormData();
				  form.append("text",JSON.stringify(param));
				  form.append("audio",blob,"audio");
			    var api = new XMLHttpRequest();
			    api.onreadystatechange = ()=>{
			      if (api.readyState==4 && api.status == 200){
							try{
								let data = JSON.parse(api.responseText);
								this.d(data);
								resolve(data);
							}catch(e){
								this.d(e);
								resolve(false);	
							}
			      }
			    };
			    //设置语音评测地址
			    var url = "https://api.stkouyu.com:8443/"+this.coreType;
			    api.open("POST", url);
			    api.setRequestHeader('Request-Index', '0');
			    //提交数据
			    api.send(form);
				},function(msg){
					resolve(false);	
				});
			}
	  });
	  return p;
	};	
	/**播放**/
	recPlay(){
		if(!this.recBlob || this.isRecoding)	return;
		var audio=this.newNode("audio");
		document.body.appendChild(audio);
		//简单利用URL生成播放地址
		audio.src=(window.URL||webkitURL).createObjectURL(this.recBlob);
		audio.play();
    audio.addEventListener('ended', function () {  
    		//不用时需要revokeObjectURL，否则霸占内存
        (window.URL||webkitURL).revokeObjectURL(audio.src);
        document.body.removeChild(audio);
    }, false);		
	};
	getDiao(i){
		if (i==0) return "";
		if (i==1) return "ˉ";
		if (i==2) return "ˊ";
		if (i==3) return "ˇ";
		if (i==4) return "ˋ";
	}
	setMoney(money){
		//TODO：保存到数据库
		this.saveItem("money",money);

		//显示金币增减的动画，未来可以做出更多特效
		let div = this.getNode("money");
		let m = parseInt(div.innerText.split(" ")[1]);
		let s = (money - m)/20;
		let i = 0;
		let I = setInterval(()=>{
			i++;
			div.innerText = "💰 " + Math.floor(m + s*i);
			if (i>20) {
				clearInterval(I);
				div.innerText = "💰 " + money;
			}
		},25);
	}
	setHonor(honor){
		//TODO：保存到数据库
		this.saveItem("honor",honor);
		this.getNode("honor").innerText = "🏅 " + honor;
	}
	setEnergy(energy){
		//TODO：保存到数据库
		this.saveItem("energy",energy);
		this.getNode("energy").innerText = "💪 " + energy;
	}
	parseInt4(str){
    var r = 0;
    for (var i = 0; i < str.length; i++)
    {
      var j = parseInt(str.substring(i, i+1));
      r += Math.pow(4, str.length - 1 - i) * j;
    }
    return r;
	}
	getLocation(id){
    if (id%5==4){
      var i = Math.floor(id/5)*4;
      return parseString4(i,4).substr(0,3);
    }else{
      var i = Math.floor(id/5)*4+(id%5);
      return parseString4(i,4);
    }
	}
	parseString4(i,l){
    var rtn = "";
    for (var k = 0; k < l; k++)
    {
      rtn += Math.floor((i % Math.pow(4, l - k)) / Math.pow(4, l - 1 - k));
    }
    return rtn;
	}	
}
export default M;